﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace FlyingEye.EntityFrameworkCore
{
    /* This class is needed for EF Core console commands
     * (like Add-Migration and Update-Database commands) */
    public class DeviceAppServiceDbContextFactory : IDesignTimeDbContextFactory<DeviceAppServiceDbContext>
    {
        public DeviceAppServiceDbContext CreateDbContext(string[] args)
        {
            DeviceAppServiceEfCoreEntityExtensionMappings.Configure();

            var configuration = BuildConfiguration();

            var connectionString = configuration.GetConnectionString("DeviceAppService");

            Console.WriteLine($"ConnectionString: ${connectionString}");

            var builder = new DbContextOptionsBuilder<DeviceAppServiceDbContext>()
                .UseMySql(connectionString, ServerVersion.Parse("8.1"));

            return new DeviceAppServiceDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../FlyingEye.DeviceAppService.DbMigrator/"))
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }
}
